package com.ruoyi.oar.api.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author saw
 * @date 2021年11月25 16:35
 * @description
 */
@Component
@Slf4j
public class CarServiceUtil {

    private static String REQUEST_URL = "https://bigdata.autosec.cn:980";

    private static String APP_KEY = "api@fc123";

    private static String SECRET_KEY = "6e4cfd177dbd06dc6e9c03ad";

    public static String getRequestUrl() {
        return REQUEST_URL;
    }

    @Value("${chefu.requestUrl}")
    public void setRequestUrl(String requestUrl) {
        REQUEST_URL = requestUrl;
    }

    public static String getAppKey() {
        return APP_KEY;
    }

    @Value("${chefu.appKey}")
    public void setAppKey(String appKey) {
        APP_KEY = appKey;
    }

    public static String getSecretKey() {
        return SECRET_KEY;
    }

    @Value("${chefu.secretKey}")
    public void setSecretKey(String secretKey) {
        SECRET_KEY = secretKey;
    }

    public static JSONObject getData(Map<String, Object> map, String interfaceCode, String path) {
        //保存日志
        Date date = new Date();
        log.debug("调用车服接口：参数={}，编码interfaceCode={}，URL={}", JSONObject.toJSONString(map), interfaceCode, REQUEST_URL + path);
        //需要传list过去
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map);
        String bodyJson = JSON.toJSONString(list);
        String assembleSecret = CommUtil.assembleSecret(SECRET_KEY);
        String body = EncryptUtil.BASE64Encrypt(EncryptUtil.DES3Encrypt(assembleSecret, bodyJson));
        String timestamp = DateUtils.dateTimeNow();
        String sign = EncryptUtil.BASE64Encrypt(Md5Util
                .getMd5String(timestamp + APP_KEY + interfaceCode + body + assembleSecret)
                .getBytes(StandardCharsets.UTF_8));
        JSONObject encryptBody = new JSONObject(16);
        encryptBody.put("appKey", APP_KEY);
        encryptBody.put("sign", sign);
        encryptBody.put("timestamp", timestamp);
        encryptBody.put("interfaceCode", interfaceCode);
        encryptBody.put("body", body);
        try {
            String resultStr = HttpRequest
                    .post(REQUEST_URL + path)
                    .charset(StandardCharsets.UTF_8)
                    .form(encryptBody)
                    //超时时间30秒
                    .setReadTimeout(100 * 1000)
                    .execute()
                    .body();
            if (StringUtils.isEmpty(resultStr)) {
                throw new ServiceException("调用异常请重试。");
            }
            JSONObject jsonResult = JsonUtil.json2bean(resultStr, JSONObject.class);
            if (!"100".equals(jsonResult.getString("state"))) {
                throw new ServiceException("调用异常：" + jsonResult.getString("errorMsg"));
            }
            String resultData = jsonResult.getString("data");
            //解密
            resultData = EncryptUtil.DES3Decrypt(EncryptUtil.BASE64Decrypt(resultData), assembleSecret);
            if (ToolUtil.isEmpty(resultData)) throw new ServiceException("调用异常请重试。");
            log.debug("调用车服接口返回json值：{}", resultData);
            return JSON.parseObject(resultData);
        } catch (Throwable e) {
            log.error("车服接口请求失败：调用 URL={} 调用编码interfaceCode={},调用时间={} ，异常描述：{}", REQUEST_URL + path, interfaceCode, timestamp, e.getMessage(), e);
            if (ToolUtil.isNotEmpty(e.getMessage()) && e.getMessage().contains("Read timed out")) {
                throw new ServiceException("请求超时，请重试");
            }
            throw new ServiceException("调用异常：" + e.getMessage());
        }
    }
}
